<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}

li {
  list-style-type: none;
}

.list-item.selected {
  background-color: #409eff; /* 选中项的背景色 */
  color: white; /* 选中项的文字色 */
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">


    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px;display: flex">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅行业名可查）"
                style="width: 20%"
                clearable></el-input>

      <el-button style="margin-left: 10px" type="primary" @click="addSpec">新增规范</el-button>

      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="specId" width="100" label="规范ID"/>
      <el-table-column sortable prop="specName" width="220" label="规范名称"/>
      <el-table-column sortable prop="username" width="150" label="创建人"/>
      <el-table-column sortable prop="description" width="150" label="描述"/>
      <el-table-column sortable prop="industryName" width="220" label="项目类型名称"/>
      <el-table-column sortable prop="fieldName" width="220" label="业务类型名称"/>
      <el-table-column sortable prop="creationTime" width="250" label="创建时间"/>
      <el-table-column sortable prop="updateTime" width="250" label="修改时间"/>
      <el-table-column sortable width="250" label="状态">
        <template #default="scope">
          <span v-if="scope.row.isDeleted === 0">使用中</span>
          <span v-else>已禁用</span>
        </template>
      </el-table-column>


      <el-table-column sortable fixed="right" label="操作" min-width="300">
        <template #default="scope">
          <el-popconfirm title="确定永久删除吗?" @confirm="deleteById(scope.row.specId)">
            <template #reference>
              <el-button link type="primary" :icon="Delete">删 除</el-button>
            </template>
          </el-popconfirm>
          <el-button link type="primary" @click="detail(scope.row)" :icon="More">详情</el-button>
          <el-button link type="primary" @click="viewSpe(scope.row)" :icon="View">查看</el-button>
          <el-button link type="primary" @click="share(scope.row)" :icon="Promotion">分享</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 15, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>
  </div>


  <!--新增弹框-->
  <!--   centerDialogVisible是一个变量，需要在script中定义一下，默认为false     -->
  <el-dialog style="margin-top: 30px" v-model="data.addDialogVisible" title="请输入新增规范的相关信息" width="40%" center>
    <el-form label-width="60px">
      <el-form-item style="margin-left: 50px" label-width="100" label="规范名称">
        <el-input v-model="data.addForm.specName" style="width: 80%;" placeholder="请输入规范名称"/>
      </el-form-item>
      <el-form-item style="margin-left: 50px" label-width="100" label="描   述">
        <el-input type="textarea" rows="4" v-model="data.addForm.description" style="width: 80%;"
                  placeholder="请输入相关描述"/>
      </el-form-item>


      <el-form-item style="margin-left: 50px;" label-width="100" label="所属项目类型">
        <el-select v-model="data.selectIndustryId" placeholder="请选择项目类型" style="width: 80%" @change="LoadDomain">
          <el-option
              v-for="item in data.fieldTableData"
              :key="item.industryId"
              :label="item.industryName"
              :value="item.industryId"
          >
            <span style="float: left">{{ item.industryName }}</span>
            <span
                style="float: right; color: var(--el-text-color-secondary); font-size: 13px;"
            >{{ item.description }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item style="margin-left: 50px;" label-width="100" label="所属业务类型">
        <el-select v-model="data.selectFieldId" placeholder="请选择业务类型" style="width: 80%">
          <el-option
              v-for="item in data.domain"
              :key="item.fieldId"
              :label="item.fieldName"
              :value="item.fieldId"
          >
            <span style="float: left">{{ item.fieldName }}</span>
            <span
                style="float: right; color: var(--el-text-color-secondary); font-size: 13px;"
            >{{ item.description }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item style="margin-left: 50px" label-width="100" label="解析文件">
        <el-tabs v-model="data.activeTab" type="border-card">
          <el-tab-pane name="upload" label="从本地上传文件进行解析" style="display: flex;justify-content: center">
            <el-upload
                multiple
                :action="uploadUrl"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="handleError"
                :on-progress="handleProgress"
            >
              <el-button type="primary">点击上传文件</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="select" label="从我的文件选择" style="text-align: center">
            <div class="infinite-list-wrapper" style="width: 100%;height: 120px;overflow: auto">
              <ul
                  v-infinite-scroll="load"
                  style="margin-left: -15%;"
                  class="list"
                  :infinite-scroll-disabled="disabled"
              >
                <li style="cursor: pointer;padding: 0 15px;box-sizing: border-box"
                    v-for="i in data.myFileData"
                    :key="i"
                    v-show="i.fileType === 'pdf'"
                    :class="{ selected: data.selectedFile === i.fileName }"
                    @click="selectFile(i.fileName,i.fileId,i.filePath)"
                    class="list-item">
                  {{ i.fileName }}
                </li>
              </ul>
              <p v-if="loading">加载中...</p>
              <p v-if="noMore">没有更多了</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>

      <el-form-item style="margin-left: 50px" label-width="100" label="状 态">
        <div class="mb-2 flex items-center text-sm">
          <el-radio-group v-model="data.addForm.isDeleted" class="ml-4">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>

    </el-form>

    <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.addDialogVisible = false">取消</el-button>
              <el-button v-show="data.activeTab === 'select'" type="primary" @click="saveAdd">确认</el-button>
            </span>
    </template>
  </el-dialog>


  <el-dialog v-model="data.shareVisible" title="分享" width="500" center>
    <el-form label-width="150px" style="padding-right: 50px" :model="data.ShareForm">
      <el-form-item label="分享链接">
        <div style="display: flex">
          <el-input style="flex: 1" v-model="data.shareLink"></el-input>
          <el-button style="margin-left: 10px" type="primary" @click="copyLink(data.shareLink)">复制</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.shareVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {computed, reactive, ref} from "vue";
import {Delete, More, Promotion, View} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {PYTHON_API_BASE_URL} from "@/config.js";
import axios from "axios";

const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userData = dataString ? JSON.parse(dataString) : null;

const data = reactive({
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  fieldTableData: [],//行业的数据
  domainTableData: [],//领域的数据
  selectedRows: [], // 选中行的数组
  //新增表单
  addForm: {
    specName: null,
    description: null,
    creatorId: userData.userId,
    isDeleted: 0
  },
  //弹窗默认关闭
  addDialogVisible: false,
  ShareForm: {},
  shareLink: '',
  shareVisible: false,
  shareSpeId: null,
  selectIndustryId: null,
  selectFieldId: null,
  domain: [],
  myFileData: [],
  dataLength: '',
  selectedFile: '',
  selectedFileId: null,
  activeTab: 'upload',//标签页切换
  selectedFilePath: '',
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  request.get(`/java/specification/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        ElMessage.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const deleteById = async (Id) => {
  try {
    const res = await request.delete("/java/specification/deleteById/" + Id);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};


//批量删除的行
const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

//批量删除
const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.specId); // 使用 specId 作为唯一标识
  if (selectedIds.length === 0) {
    // 没有选中任何行
    return;
  }
  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定删除选中的选项吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    try {
      const res = await request.delete('/java/specification/delete/' + selectedIds);
      Load();
    } catch (error) {
      ElMessage.error('批量删除失败：', error);
    }
  }
};


const handleSuccess = (response, file, fileList) => {
  ElMessage.success(`成功上传: ${file.name}`);
};

const handleError = (err, file, fileList) => {
  ElMessage.error(`上传失败: ${file.name}`);
};


// 实现beforeUpload方法
const beforeUpload = (file) => {
  if (data.addForm.specName == null || data.selectIndustryId == null || data.selectFieldId == null) {
    ElMessage.info("请完善相关信息后再上传文件")
    return false;
  }

  // 例如检查文件大小，不允许上传超过10MB的文件
  const isTooLarge = file.size / 1024 / 1024 > 100;
  if (isTooLarge) {
    // 使用Element UI的消息提示组件，显示错误信息
    ElMessage.error('文件大小不能超过 100MB!');
    return false;  // 拦截文件上传
  }

  // (可选) 还可以检查文件类型等其他条件
  const isPDF = file.type === 'application/pdf';
  if (!isPDF) {
    ElMessage.error('只能上传pdf文件!');
    return false;  // 拦截文件上传
  }

  // 如果通过了所有检查，则返回true或者没有返回值（implicit return undefined），允许上传继续
}


const addSpec = () => {

  data.addDialogVisible = true;

  request.get(`/java/industry/category/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        data.fieldTableData = response.data.records;
      })
      .catch((error) => {
        ElMessage.error('请求发生错误:', error);
      })
      .finally(() => {
      });

  request.get(`/java/field/category/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        data.domainTableData = response.data.records;
      })
      .catch((error) => {
        ElMessage.error('请求发生错误:', error);
      })
      .finally(() => {
      });

  loadMyFile()
}

const handleProgress = () => {
  data.addDialogVisible = false
}


const detail = (row) => {
  location.href = '/detail?specId=' + row.specId
}


const viewSpe = (row) => {
  location.href = '/view?specId=' + row.specId + '&specName=' + row.specName
}

const copyLink = (link) => {
  let _input = document.createElement("input");   // 直接构建input
  _input.value = link;  // 设置内容
  document.body.appendChild(_input);    // 添加临时实例
  _input.select();   // 选择实例内容
  document.execCommand("Copy");   // 执行复制
  document.body.removeChild(_input)
  ElMessage.success("复制链接成功")
}

const share = (row) => {
  data.ShareForm = JSON.parse(JSON.stringify(row));//将该行数据（多个字段）存入data.form
  data.shareLink = '';
  data.shareVisible = true;
  data.shareSpeId = row.specId;
  saveShare(row.specName)
}

const saveShare = (specName) => {
  if (data.shareLink) {//有了链接，点确定不能再生成了
    data.shareVisible = false
    return;
  }
  let currentUrl = location.href.substring(0, location.href.indexOf('/specificationLibrary'))
  data.shareLink = currentUrl + '/view?specId=' + data.shareSpeId + '&specName=' + specName
}

//加载行业下的领域
const LoadDomain = () => {
  data.domain = []
  data.selectFieldId = null
  // 仅当选择了一个行业时才发起请求
  if (data.selectIndustryId) {
    request.get(`/java/field/category/getFiledByIndustryId?IndustryId=${data.selectIndustryId}`)
        .then((response) => {
          data.domain = response.data;
        })
        .catch((error) => {
          ElMessage.error('请求发生错误:', error);
        })
  }
};

const count = ref(0)
const loading = ref(false)
const noMore = computed(() => count.value >= data.dataLength)
const disabled = computed(() => loading.value || noMore.value)

//滚动的时候触发
const load = () => {
  loading.value = true
  setTimeout(() => {
    count.value += 1
    loading.value = false
  }, 100)
}



const loadMyFile = () => {
  request.get(`/java/file/findFileByUserId?UserId=${userData.userId}`)
      .then((response) => {
        data.myFileData = response.data
        data.dataLength = response.data.length
      })
      .catch((error) => {
        ElMessage.error('请求发生错误:', error);
      })
      .finally(() => {
      });
}

const selectFile = (fileName, fileId, filePath) => {
  ElMessage.info("已选中文件" + fileId + ":" + fileName) // 打印文件名
  data.selectedFile = fileName // 记录选中的文件名
  data.selectedFileId = fileId
  data.selectedFilePath = filePath
  // 其他处理，如果有的话
}


const saveAdd = () => {
  if (data.addForm.specName == null || data.selectIndustryId == null || data.selectFieldId == null || data.selectedFile === '') {
    ElMessage.info("请完善相关信息并选择文件后再确认")
    return false;
  }
  axios.get(PYTHON_API_BASE_URL + `/download_file/?file_url=` + data.selectedFilePath + '&industryCategoryId='
      + data.selectIndustryId + '&fieldCategoryId=' + data.selectFieldId + '&specName=' + data.addForm.specName
      + '&creatorId=' + userData.userId + '&description=' + data.addForm.description).then((res) => {
    console.log(res)
  })
  data.addDialogVisible = false
}

// 计算属性来构建包含ID的上传URL
const uploadUrl = computed(() => {
  return PYTHON_API_BASE_URL + `/upload/?creatorId=${data.addForm.creatorId}&industryCategoryId=${data.selectIndustryId}&fieldCategoryId=${data.selectFieldId}&isDeleted=${data.addForm.isDeleted}&specName=${data.addForm.specName}&description=${data.addForm.description}`;
});

</script>
